﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using CloudShot.Utils.Converters;

namespace CloudShot.Controls
{
  internal class AutoSizeTextBox : TextBox
  {
    private static readonly Bitmap _measurementBitmap = new Bitmap(1, 1);
    private bool _autoSize = true;

    [Browsable(true)]
    [DefaultValue(true)]
    public override bool AutoSize
    {
      get { return _autoSize; }
      set
      {
        _autoSize = value;
        ArrangeTextBoxSize();
      }
    }

    public void ArrangeTextBoxSize()
    {
      if (!AutoSize)
        return;

      var format = new StringFormat(StringFormat.GenericDefault)
      {
        Alignment = TextAlign.ToStringAlignment()
      };

      using (var graphics = Graphics.FromImage(_measurementBitmap))
      {
        const int padding = 10;

        //NOTE: this is necessary to correctly measure the size of a text box with empty lines at the end
        string measurementText = Text.Replace("\n", "\n ");

        SizeF textSize = graphics.MeasureString(measurementText, Font, MinimumSize.Width, format);
        Size = new Size((int)textSize.Width + padding, (int)textSize.Height + padding);
      }
    }

    protected override void OnTextChanged(EventArgs e)
    {
      base.OnTextChanged(e);
      ArrangeTextBoxSize();
    }
  }
}